package com.kefu.common.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;

//订阅消息
public class SubClient {
    private static Logger logger = LoggerFactory.getLogger(SubClient.class);
    private static JedisPool jedisPool =JedisUtils.jedisPool;
    private static Jedis jedis = jedisPool.getResource();

    /**
     * 接收消息。在main方法调用后，会一直执行下去。当有发布对应消息时，就会在jedisPubSub中接收到！
     *
     * @param jedisPubSub
     * @param channels
     */
    public static void subscribeMsg(JedisPubSub jedisPubSub, String channels) {
        try {
            jedis.subscribe(jedisPubSub, channels);
            logger.info("subscribeMsg {} = {}", jedisPubSub, channels);
        } catch (Exception e) {
            logger.error("subscribeMsg {} = {}", jedisPubSub, channels, e);
        }
    }

    /**
     * 模式订阅
     * @param
     */
    public static void psubscribeMsg(JedisPubSub jedisPubSub, String patterns) {
        try {
            jedis.psubscribe(jedisPubSub, patterns);
            logger.info("subscribeMsg {} = {}", jedisPubSub, patterns);
        } catch (Exception e) {
            logger.error("subscribeMsg {} = {}", jedisPubSub, patterns, e);
        }
    }
}